#include <QApplication>
#include <QLabel>
#include <QString>
#include <ctime>
#include <rclcpp/rclcpp.hpp>
#include <sys_status/msg/system_status.hpp>

class StatusSubscriper : public rclcpp::Node
{
private:
    /* data */
    rclcpp::Subscription<sys_status::msg::SystemStatus>::SharedPtr _subscriper;
    std::shared_ptr<QLabel> _label;
    QString msg_to_qstring(const sys_status::msg::SystemStatus::SharedPtr msg)
    {
        // 假设有一个整型变量表示自1970年1月1日以来的秒数
        std::chrono::seconds seconds(msg->stamp.sec);

        // 使用chrono::system_clock将秒数转换为time_point
        auto time_point = std::chrono::system_clock::time_point(seconds);

        // 获取本地时间
        auto local_time = std::chrono::system_clock::to_time_t(time_point);
        std::tm *timeinfo = std::localtime(&local_time);

        // 或者直接使用put_time，这是一个更现代且更简洁的方法
        std::stringstream ss;
        ss << std::put_time(timeinfo, "%Y-%m-%d %H:%M:%S");

        std::stringstream str;
        str << "========= System Status ========= \n"
            << "time\t" << ss.str() << "\n"
            << "host\t" << msg->host_name << "\n"
            << "cpu\t" << msg->cpu_percent << "\n"
            << "mem(per)\t" << msg->memory_percent << "\n"
            << "mem(tol)\t" << msg->memory_total << "\n"
            << "mem(ava)\t" << msg->memory_available << "\n"
            << "net(O)\t" << msg->net_sent << "\n"
            << "net(I)\t" << msg->net_recieve << "\n";

        return QString::fromStdString(str.str());
    }
    void sub_cb(const sys_status::msg::SystemStatus::SharedPtr msg)
    {
        _label->setText(msg_to_qstring(msg));
    }

public:
    StatusSubscriper(const std::string &node_name) : rclcpp::Node(node_name)
    {
        _subscriper = create_subscription<sys_status::msg::SystemStatus>(
            "system_status", 10,
            std::bind(&StatusSubscriper::sub_cb, this, std::placeholders::_1));
        _label = std::make_shared<QLabel>(
            msg_to_qstring(std::make_shared<sys_status::msg::SystemStatus>()));
        _label->show();
    }
    ~StatusSubscriper() {}
};

int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);
    QApplication app(argc, argv);
    auto node = std::make_shared<StatusSubscriper>("status_subscriper");
    std::thread spin_thd([&]() -> void { rclcpp::spin(node); });
    app.exec();
    if (spin_thd.joinable())
    {
        spin_thd.join();
    }
    return 0;
}